package vip.meeet.algorithm.str;



public class Num29 {

    public static void main(String[] args) {

        System.out.println(divide(10,3));
        System.out.println(divide(7,-3));
        System.out.println(divide(-2147483648,2));
    }

    public static int divide(int dividend, int divisor) {
        if(dividend == 0){
            return 0;
        }
        if(dividend == divisor){
            return 1;
        }
        if(dividend == -2147483648 && divisor == -1){
            return 2147483647;
        }

        int times = 0;
        boolean isNeg;
        if ((dividend >0 && divisor >0) || (dividend<0 && divisor <0)){
            isNeg = false;
        }else {
            isNeg = true;
        }
        if(divisor == 1){
            return dividend;
        }
        if(divisor == -1){
            return -dividend;
        }
        if(divisor < 0){
            if(divisor == -2147483648){
                return 0;
            }else {
                divisor = -divisor;
            }
        }

        if(dividend < 0){
            if(dividend == -2147483648){
                if(divisor < 0) {
                    dividend = (int) (2147483648L + divisor);
                }else {
                    dividend = (int) (2147483648L - divisor);
                }
                times += 1;
            }else {
                dividend = -dividend;
            }
        }
        if(divisor == 2){
            times += (dividend >> 1);
        }else if(divisor == 4){
            times += (dividend >>> 2);
        }else if(divisor == 8){
            times += (dividend >>> 3);
        }else if(divisor == 16){
            times += (dividend >>> 4);
        }else {
            while (dividend >= divisor) {
                dividend -= divisor;
                times++;
            }
        }
        if(isNeg){
            return -times;
        }else {
            return times;
        }

    }

}
